package com.lvyq.myplayer.ui.activity.search

/**
 * 文件描述：SearchActivity
 * 作者：lvyq
 * 创建时间：2025-05-07
 * 修改时间：2025-05-07
 */
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lvyq.myplayer.R
import com.lvyq.myplayer.adapter.search.SearchAdapter
import com.lvyq.myplayer.model.index.IndexHotSongBean
import com.lvyq.myplayer.parcelable.SongInfoData
import com.lvyq.myplayer.ui.activity.AudioPlayerActivity
import com.lvyq.myplayer.util.NetworkUtils
import com.lvyq.myplayer.util.ThreadUtil
import com.lvyq.myplayer.util.URLProviderUtils

class SearchActivity : AppCompatActivity() {

    private lateinit var searchEditText: EditText
    private lateinit var resultsRecyclerView: RecyclerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)

        // 初始化视图
        searchEditText = findViewById(R.id.searchEditText)
        resultsRecyclerView = findViewById(R.id.searchResultsRecyclerView)

        // 设置RecyclerView
        resultsRecyclerView.layoutManager = LinearLayoutManager(this)
        resultsRecyclerView.adapter = SearchAdapter(object :SearchAdapter.OnItemClickListener{
            override fun onItemClick(position: Int, data: SongInfoData) {
                var lst = ArrayList<SongInfoData>()
                var intent = Intent(this@SearchActivity, AudioPlayerActivity::class.java)
                intent.putExtra("position",0)
                intent.putExtra("data",data)
                lst.add(data)
                intent.putParcelableArrayListExtra("songLst",lst)
                startActivity(intent)
            }

        })

        // 设置搜索监听
        searchEditText.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch(searchEditText.text.toString())
                true
            }
            false
        }
    }

    private fun performSearch(query: String) {
        val url = URLProviderUtils.search(
            query)
        NetworkUtils.get(
            url = url,
            responseClass = IndexHotSongBean::class.java,
            successCallback = { pageData ->
                (resultsRecyclerView.adapter as SearchAdapter).updateData(pageData)
            },
            errorCallback = { errorMsg ->
                Log.e("SingerSongPagerFragment", "加载失败：$errorMsg")
            }
        )
    }


}